import { createRouter, createWebHistory } from 'vue-router'
import loginView from '@/views/login/index.vue'
import registerView from '@/views/register/index.vue'
import homeView from '@/views/home/home.vue'
import indexView from '@/views/home/index.vue'
import claView from '@/views/home/cla.vue'
import cartView from '@/views/home/cart.vue'
import myView from '@/views/home/my.vue'
import goodsView from '@/views/goods/index.vue'
import detailView from '@/views/detail/index.vue'
const router = createRouter({
  history: createWebHistory(import.meta.env.BASE_URL),
  routes: [
    // 路由重定向
    { path: '/', redirect: '/home/index' },
    { path: '/login', name: 'login', component: loginView },
    { path: '/register', name: 'register', component: registerView },
    {
      path: '/home', name: 'home', component: homeView, children: [
        { path: 'index', name: 'index', component: indexView },
        { path: 'cla', name: 'cla', component: claView },
        { path: 'cart', name: 'cart', component: cartView },
        { path: 'my', name: 'my', component: myView },

      ]
    },
    //商品列表
    { path: '/goods/:cat_name', name: 'goods', component: goodsView },
    //商品详情
    { path: '/detail/:goods_id', name: 'detail', component: detailView },
  ],
})
// 导航守卫  未登录状态下  购物车页面 和 我的页面 禁止进入
router.beforeEach((to,from,next)=>{
  // 如果进入的是购物车页面和我的页面 判断一下
  if(to.fullPath== '/home/cart' || to.fullPath == '/home/my'){
    let token = localStorage.getItem('token')
    if(token){
      next()
    }else{
      // token 不存在的情况下
      next('/login')
    }
  }else{
    // 进入的 分类 和  首页
    next()
  }
})

export default router
